package com.linxianqin.springbootVue.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.linxianqin.springbootVue.domain.constant.UserConstants;
import com.linxianqin.springbootVue.domain.convert.SysUserConvert;
import com.linxianqin.springbootVue.domain.dto.SysPostDTO;
import com.linxianqin.springbootVue.domain.dto.SysRoleDTO;
import com.linxianqin.springbootVue.domain.dto.SysUserDTO;
import com.linxianqin.springbootVue.domain.entity.SysPost;
import com.linxianqin.springbootVue.domain.entity.SysRole;
import com.linxianqin.springbootVue.domain.entity.SysUser;
import com.linxianqin.springbootVue.domain.query.SysUserQuery;
import com.linxianqin.springbootVue.manage.exception.CustomException;
import com.linxianqin.springbootVue.mapper.SysUserMapper;
import com.linxianqin.springbootVue.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linxianqin.springbootVue.utils.DateUtils;
import com.linxianqin.springbootVue.utils.SecurityUtils;
import com.linxianqin.springbootVue.utils.text.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author lxq
 * @since 2020-12-12
 */
@Slf4j
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    private final SysDeptService sysDeptService;
    private final SysUserRoleService userRoleService;
    private final SysUserPostService userPostService;
    private final SysRoleService roleService;
    private final SysPostService postService;
    private final SysDeptService deptService;
    public SysUserServiceImpl(SysDeptService sysDeptService,SysUserRoleService userRoleService,
                              SysUserPostService userPostService,SysRoleService roleService,
                              SysPostService postService,SysDeptService deptService){
        this.sysDeptService=sysDeptService;
        this.userRoleService=userRoleService;
        this.userPostService=userPostService;
        this.roleService=roleService;
        this.postService=postService;
        this.deptService=deptService;
    }
    @Override
    public SysUserDTO selectUserByUserName(String username) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUser::getUserName,username);
        return SysUserConvert.INSTANCE.entity2dto(baseMapper.selectOne(queryWrapper));
    }

    /**
     * 根据条件分页查询用户列表
     *
     * @param query 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public Page<SysUserDTO> selectUserPage(Page<SysUserDTO> page, SysUserQuery query) {
        Page<SysUser> entityPage = SysUserConvert.INSTANCE.dto2entity(page);
        LambdaQueryWrapper<SysUser> queryWrapper=new QueryWrapper<SysUser>().lambda();
        if (StringUtils.isNotNull(query.getStatus())){
            queryWrapper.eq(SysUser::getStatus,query.getStatus());
        }
        if (StringUtils.isNotNull(query.getUserName())){
            queryWrapper.like(SysUser::getUserName,query.getUserName());
        }
        if (StringUtils.isNotNull(query.getPhonenumber())){
            queryWrapper.like(SysUser::getPhonenumber,query.getPhonenumber());
        }
        List<Long> deptIds = sysDeptService.selectDeptListInDept(query.getDeptId());
        deptIds.add(query.getDeptId());
        if (StringUtils.isNotNull(query.getDeptId())){
            queryWrapper.in(SysUser::getDeptId,deptIds);
        }
        if (StringUtils.isNotNull(query.getParams())){
            Map<String, Object> params = query.getParams();
            Object beginTime = params.get("beginTime");
            log.info("开始时间：{}",beginTime);
            if (beginTime!=null){
                queryWrapper.ge(SysUser::getCreateTime,beginTime);
            }
            Object endTime =params.get("endTime");
            log.info("结束时间：{}",endTime);
            if (beginTime!=null){
                endTime = DateUtils.addOneDay(DateUtils.dateTime("yyyy-MM-dd", endTime.toString()));
                queryWrapper.le(SysUser::getCreateTime,endTime);
            };
        }
        Page<SysUser> selectPage = baseMapper.selectPage(entityPage, queryWrapper);
        return SysUserConvert.INSTANCE.entity2dto(selectPage);
    }

    /**
     * 查询部门是否存在用户
     *
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long deptId) {
        LambdaQueryWrapper<SysUser> queryWrapper = new QueryWrapper<SysUser>().lambda();
        queryWrapper.eq(SysUser::getDeptId,deptId).eq(SysUser::getDeleted,"0");
        return baseMapper.selectCount(queryWrapper)>0;
    }
    /**
     * 校验手机号码是否唯一
     *
     * @param userName 用户名称
     * @return 结果
     */
    @Override
    public String checkUserNameUnique(String userName) {
        LambdaQueryWrapper<SysUser> queryWrapper = new QueryWrapper<SysUser>().lambda();
        queryWrapper.eq(SysUser::getUserName,userName);
        SysUser sysUser = baseMapper.selectOne(queryWrapper);
        if (StringUtils.isNotNull(sysUser))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }
    /**
     * 校验用户名称是否唯一
     *
     * @param userDTO 用户信息
     * @return
     */
    @Override
    public String checkPhoneUnique(SysUserDTO userDTO) {
        Long userId = StringUtils.isNull(userDTO.getUserId()) ? -1L : userDTO.getUserId();
        LambdaQueryWrapper<SysUser> queryWrapper = new QueryWrapper<SysUser>().lambda();
        queryWrapper.eq(SysUser::getPhonenumber,userDTO.getPhonenumber());
        SysUser sysUser = baseMapper.selectOne(queryWrapper);
        if (StringUtils.isNotNull(sysUser)&& sysUser.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }
    /**
     * 校验email是否唯一
     *
     * @param userDTO 用户信息
     * @return
     */
    @Override
    public String checkEmailUnique(SysUserDTO userDTO) {
        Long userId = StringUtils.isNull(userDTO.getUserId()) ? -1L : userDTO.getUserId();
        LambdaQueryWrapper<SysUser> queryWrapper = new QueryWrapper<SysUser>().lambda();
        queryWrapper.eq(SysUser::getEmail,userDTO.getEmail());
        SysUser info = baseMapper.selectOne(queryWrapper);
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param userDTO 用户信息
     */
    @Override
    public void checkUserAllowed(SysUserDTO userDTO)
    {
        if (StringUtils.isNotNull(userDTO.getUserId()) && userDTO.isAdmin())
        {
            throw new CustomException("不允许操作超级管理员用户");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserByIds(List<Long> userIds) {
        for (Long userId : userIds)
        {
            checkUserAllowed(new SysUserDTO(userId));
        }
        // 删除用户与角色关联
        userRoleService.deleteUserRoleByUserIds(userIds);
         // 删除用户与岗位关联
        userPostService.deleteUserPostByUserIds(userIds);
        return baseMapper.deleteBatchIds(userIds);
    }
    /**
     * 新增保存用户信息
     *
     * @param userDTO 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertUser(SysUserDTO userDTO) {
        userDTO.setCreateBy(SecurityUtils.getUsername());
        userDTO.setPassword(SecurityUtils.encryptPassword(userDTO.getPassword()));
        // 新增用户信息
        SysUser sysUser = SysUserConvert.INSTANCE.dto2entity(userDTO);
        int rows = baseMapper.insert(sysUser);
        userDTO.setUserId(sysUser.getUserId());
        // 新增用户岗位关联
        userPostService.insertUserPost(userDTO);
        // 新增用户与角色管理
        userRoleService.insertUserRole(userDTO);
        return rows;
    }
    /**
     * 修改保存用户信息
     *
     * @param userDTO 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUser(SysUserDTO userDTO) {
        userDTO.setUpdateBy(SecurityUtils.getUsername());
        Long userId = userDTO.getUserId();
        // 删除用户与角色关联
        userRoleService.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        userRoleService.insertUserRole(userDTO);
        // 删除用户与岗位关联
        userPostService.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        userPostService.insertUserPost(userDTO);
        return updateById(SysUserConvert.INSTANCE.dto2entity(userDTO));

    }
    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRoleDTO> list = roleService.selectRolesByUserName(userName);
        StringBuffer idsStr = new StringBuffer();
        for (SysRoleDTO role : list)
        {
            idsStr.append(role.getRoleName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString()))
        {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }
    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName) {

        List<SysPostDTO> list = postService.selectPostsByUserName(userName);
        StringBuffer idsStr = new StringBuffer();
        for (SysPostDTO post : list)
        {
            idsStr.append(post.getPostName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString()))
        {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }
    /**
     * 根据条件分页查询用户列表
     *
     * @param query 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public Page<SysUserDTO> selectUserDeptPage(Page<SysUserDTO> page, SysUserQuery query) {
        //设置偏移量，从那开始
        query.setCurrent((page.getCurrent()-1)*page.getSize());
        //设置查询多少个，页面大小
        query.setSize(page.getSize());
        //分页查询
        List<SysUser> userList = baseMapper.selectUserList(query);
        //构造查询条件，查询个数
        LambdaQueryWrapper<SysUser> queryWrapper=new QueryWrapper<SysUser>().lambda();
        if (StringUtils.isNotNull(query.getStatus())){
            queryWrapper.eq(SysUser::getStatus,query.getStatus());
        }
        if (StringUtils.isNotNull(query.getPhonenumber())){
            queryWrapper.like(SysUser::getPhonenumber,query.getPhonenumber());
        }
        if (StringUtils.isNotNull(query.getUserName())){
            queryWrapper.like(SysUser::getUserName,query.getUserName());
        }
        if (StringUtils.isNotNull(query.getParams())){
            Map<String, Object> params = query.getParams();
            Object beginTime = params.get("beginTime");
            if (beginTime!=null){
                queryWrapper.ge(SysUser::getCreateTime,beginTime);
            }
            Object endTime = params.get("endTime");
            if (beginTime!=null){
                endTime = DateUtils.addOneDay(DateUtils.dateTime("yyyy-MM-dd", endTime.toString()));
                queryWrapper.le(SysUser::getCreateTime,endTime);
            };
        }
        page.setTotal(baseMapper.selectCount(queryWrapper));
        page.setRecords(SysUserConvert.INSTANCE.entity2dto(userList));
        return (page);
    }
    /**
     * 修改用户基本信息
     *
     * @param userDTO 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUserDTO userDTO) {
        return baseMapper.updateById(SysUserConvert.INSTANCE.dto2entity(userDTO));
    }
    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param encryptPassword 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String encryptPassword) {
        LambdaUpdateWrapper<SysUser> updateWrapper = new UpdateWrapper<SysUser>().lambda();
        updateWrapper.eq(SysUser::getUserName,userName);
        SysUser user = new SysUser();
        user.setPassword(encryptPassword);
        return baseMapper.update(user,updateWrapper);
    }

    @Override
    public boolean updateUserAvatar(String username, String avatar) {
        LambdaUpdateWrapper<SysUser> updateWrapper = new UpdateWrapper<SysUser>().lambda();
        updateWrapper.eq(SysUser::getUserName,username);
        SysUser user = new SysUser();
        user.setAvatar(avatar);
        return baseMapper.update(user,updateWrapper)>0;
    }
}
